package com.xuecheng.content.service.impl;

import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.service.CourseCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class CourseCategoryServiceImpl implements CourseCategoryService {
    @Autowired
    CourseCategoryMapper courseCategoryMapper;
    @Override
    public List<CourseCategoryTreeDto> queryTreeNode(String id) {
        //获取查询出的所有集合
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);
        //将集合转化为map集合，key为id，value为集合里的元素本身,方便通过id寻找父类
        Map<String, CourseCategoryTreeDto> treeDtoMap = courseCategoryTreeDtos.stream().filter(key -> !id.equals(key.getId())).collect(Collectors.toMap(key -> key.getId(), value -> value, (key1, key2) -> key2));
        //创建一个最终返回结果的集合
        List<CourseCategoryTreeDto> list=new ArrayList<>();
        //对集合进行遍历,过滤掉根节点
        courseCategoryTreeDtos.stream().filter(item -> !item.getId().equals(id)).forEach(item->{
            //如果父类是根节点则添加到最终集合里
            if (item.getParentid().equals(id)){
                list.add(item);
            }
            //如果该节点的父节点能够查到，则给父节点的子节点属性上添加值
            CourseCategoryTreeDto parentDto = treeDtoMap.get(item.getParentid());
            if (parentDto!=null){
                if (parentDto.getChildrenTreeNodes()==null) {
                    parentDto.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDto>());
                }
                parentDto.getChildrenTreeNodes().add(item);
            }
        });
        return list;
    }
}
